package com.example.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Random;
import java.util.UUID;

public class LogMdcDemo {
    // Logback 使用 SLF4J 的 API
    private static final Logger logger = LoggerFactory.getLogger(LogbackExample.class);
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    // 模拟设置一个跟踪码
                    MDC.put("traceCode", getUUID());
                    MDC.put("keyId","111");
                    for (int i1 = 0; i1 < 10; i1++) {
                        System.out.println(MDC.get("traceCode"));
                        MDC.remove("keyId");
                        logger.info(i1+"This is a log message with trace code.");
                        System.out.println(MDC.get("keyId"));
                        try {
                            int random = getRandom();
                            Thread.sleep(random);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MDC.clear();
                }
            }).start();
        }
    }

    private static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    private static int getRandom(){
        Random random = new Random();
        int randomNumber = 1000 + random.nextInt(4001); // 生成1000到2000之间的随机数
        return randomNumber;
    }
}